package cpr;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import cpr.context.CommandContext;
/*
 * 
 * set HL_CSV data\zgetcprdemo_tmp.txt
 * set HL_CSV data\qube_rule_1_score_12288
 * set VERBOSE no
 * set IMAGE_SCORE 0,3,3,0,0
 * cmd HL-IMAGE-CUBE
 * help
 * 
 * 
 */
public class Shell {
	private Properties properties = null;
	public Shell(Properties props) {
		this.properties = props;
	}
	

	public void run() {
		CommandContext ctx = new CommandContext(System.out, properties);
        	try {
        		String[] cmds = ctx.getContext().getStartupCommands();
        		if (cmds!=null) {
        			for (int i = 0; i < cmds.length; i++) {
                		ctx.pushCommand(ctx.getConsolePrefix(), cmds[i]);
					}
        		}
            String line=null;
            PrintWriter out = new PrintWriter(System.out);
            UserInputThread userInputThread = new UserInputThread(ctx);
            userInputThread.start();
            Printer.open();
            boolean exit = false;
            while (!exit) { //&&ctx.hasCommand(ctx.getConsolePrefix())
            	line = "";
            	if (ctx.hasCommand(ctx.getConsolePrefix())) {
                	line = (String)ctx.popCommand(ctx.getConsolePrefix());
            	}
            	if (!"".equals(line.trim())) {
                    out.flush();
                    Printer.printlnToSecondaryPrinter(line);
                    if ("exit".equalsIgnoreCase(line.trim())) {
            			exit = true;
            		} else {
            			ctx.execute(line.trim());
            		}
            	}
            	Thread.sleep(100);
            }
            Printer.close();
        } catch (Exception ex) {
            
        }

	}
	public static void main(String[] args) {
		//Main.init(args);
		Shell splitter = new Shell(readProps(args));
		splitter.run();
	}
	
    public  static Properties readProps(String[] args) {
   	 // Read properties file.
       Properties properties = new Properties();
       StringBuffer sb = new StringBuffer();
       
       if (args.length==0)  {
       	   Printer.print("Specify .properties file as parameter!!!\n");
       	   System.exit(1);
       }
       try {
       	   Printer.print("Reading "+args[0]+" for properties\n");
           properties.load(new FileInputStream(args[0]));

       } catch (IOException e) {
       	e.printStackTrace();
       }
       return properties;
   }

}